package application;

import gui.AppDetailsNote;
import gui.AppPanelAuthor;
import gui.AppPanelChapter;
import gui.AppPanelChapterOverview;
import gui.AppPanelCharacter;
import gui.AppPanelCharacterOverview;
import gui.AppPanelFaction;
import gui.AppPanelFactionOverview;
import gui.AppPanelLocation;
import gui.AppPanelLocationOverview;
import gui.AppPanelPlot;
import gui.AppPanelPlotOverview;
import gui.AppPanelScene;
import gui.AppPanelSceneOverview;
import gui.AppPanelSettings;
import gui.AppPanelStory;
import gui.AppPanelStoryManager;
import gui.NotePanel;
import gui.StoryLineAppGUI;

import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collections;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.query.Query;

public class StoryLine2edit implements TreeSelectionListener, ActionListener,
		ListSelectionListener {

	// db4o database file:
	static String dbFile;

	// Roles for the char object:
	private String[] Roles = { "Main Cast", "Support Cast", "Extras" };
	private String[] Level = { "Rookie", "Beginner", "Trained", "Professional",
			"Master" };
	private String[] Affilation = { "Party", "Neutral", "Opposition",
			"Beneficial", "Unknown" };
	private String[] SceneStatus = { "design", "concept", "in the works",
			"done" };
	private String[] Gender = { "female", "male" };
	private String[] folders = { "database", "files", "export", "images" };
	static String story;
	// ArrayLists to store the objects

	// workdata
	private static Story activeStory = new Story();
	public static ArrayList<Chapter> activeChapters = new ArrayList<Chapter>();
	public ArrayList<Character> activeCharacters = new ArrayList<Character>();
	public ArrayList<Location> activeLocations = new ArrayList<Location>();
	public ArrayList<Note> activeNotes = new ArrayList<Note>();
	public ArrayList<Plot> activePlots = new ArrayList<Plot>();
	public ArrayList<Faction> activeFactions = new ArrayList<Faction>();
	public ArrayList<String> stories = new ArrayList<String>();
	public ArrayList<Note> chapterNotes = new ArrayList<Note>();
	public Author StoryAuthor;

	public static Settings settings = new Settings();

	// active objects
	private Chapter selectedChapter = new Chapter();
	private Scene selectedScene = new Scene();
	private Character selectedCharacter = new Character();
	private Location selectedLocation = new Location();
	private Faction selectedFaction = new Faction();
	private Plot selectedPlot = new Plot();
	private Note selectedNote = new Note();

	// tree selections
	private JTree storytree = new JTree();
	private TreePath path;
	private Object elements[];
	private String treeSelectedItem;
	// JLists
	private DefaultListModel chapterNoteList = new DefaultListModel();
	private DefaultListModel chapterList = new DefaultListModel();
	private JList listChapters = new JList(chapterList);

	private DefaultListModel plotSceneList = new DefaultListModel();
	private JList listPlotScenes = new JList(plotSceneList);

	private DefaultListModel sceneList = new DefaultListModel();
	private JList listScenes = new JList(sceneList);

	private DefaultListModel charsList = new DefaultListModel();
	private JList listChars = new JList(charsList);

	private DefaultListModel allCharsList = new DefaultListModel();
	private JList listAllChars = new JList(allCharsList);

	private DefaultListModel selCharsList = new DefaultListModel();
	protected JList listSelChars = new JList(selCharsList);

	private DefaultListModel locationList = new DefaultListModel();
	private JList listLocations = new JList(locationList);

	private DefaultListModel factionList = new DefaultListModel();
	private JList listFactions = new JList(factionList);

	private DefaultListModel plotList = new DefaultListModel();
	private JList listPlots = new JList(plotList);

	private DefaultListModel noteList = new DefaultListModel();
	private JList listNotes = new JList(noteList);

	private DefaultListModel storyList = new DefaultListModel();
	private JList listStory = new JList(noteList);

	// the tree
	private Boolean isExpanded = false;
	private DefaultMutableTreeNode treeStory;

	// GUI
	private AppPanelStoryManager panelStoryManager = new AppPanelStoryManager();
	private AppPanelStory panelStory = new AppPanelStory();
	private AppPanelChapter panelChapter = new AppPanelChapter();
	private AppPanelChapterOverview panelChapterOverview = new AppPanelChapterOverview();
	private AppPanelScene panelScene = new AppPanelScene();
	private AppPanelSceneOverview panelSceneOverview = new AppPanelSceneOverview();
	private AppPanelCharacter panelCharacter = new AppPanelCharacter();
	private AppPanelCharacterOverview panelCharacterOverview = new AppPanelCharacterOverview();
	private AppPanelLocation panelLocation = new AppPanelLocation();
	private AppPanelLocationOverview panelLocacionOverview = new AppPanelLocationOverview();
	private AppPanelFaction panelFaction = new AppPanelFaction();
	private AppPanelFactionOverview panelFactionOverview = new AppPanelFactionOverview();
	private AppPanelPlot panelPlot = new AppPanelPlot();
	private AppPanelPlotOverview panelPlotOverview = new AppPanelPlotOverview();
	private AppPanelAuthor panelAuthor;

	private JPanel detailsNote = new AppDetailsNote();

	private static String homePath = System.getProperty("user.home").toString();
	private static String configFile;
	private static String storyPath;

	public static void main(String[] args) {
		firstRun();
		loadSettings();
		try {
			// Set System L&F
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (UnsupportedLookAndFeelException e) {
			// handle exception
		} catch (ClassNotFoundException e) {
			// handle exception
		} catch (InstantiationException e) {
			// handle exception
		} catch (IllegalAccessException e) {
			// handle exception
		}
		try {
			StoryLineAppGUI window = new StoryLineAppGUI();
			window.frmStoryline.setLocationRelativeTo(null);
			window.frmStoryline.setVisible(true);

		} catch (Exception e) {
			e.printStackTrace();
		}
		new StoryLine2edit();
	}

	private static void firstRun() {
		// check for settings file in home
		File folder = new File(homePath, ".storyLine");
		if (folder.exists()) {
			System.out.println("folder exists");
		} else {
			folder.mkdir();
		}
		File config = new File(folder, "StoryLine.conf");
		configFile = config.toString();
		if (config.exists()) {
			System.out.println("config exists");
		} else {
			try {
				config.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			new initSettings(config.toString());
		}
	}

	public StoryLine2edit() {
		

		
		buildUI();
		storySelection();
		initPanels();
		localizeUI();
		addActionListners();
	}

	private void initPanels() {

		panelAuthor = new AppPanelAuthor(dbFile, activeStory);
	}

	public void clearDetails() {
		StoryLineAppGUI.panelSide.removeAll();
		StoryLineAppGUI.panelSide.repaint();
	}

	private static void loadSettings() {

		ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded
				.newConfiguration(), configFile);

		try {
			ObjectSet<Settings> result = db.queryByExample(Settings.class);
			while (result.hasNext()) {
				Settings tmp = (Settings) result.next();
				settings = tmp;
			}
		}

		finally {
			db.close();
		}
	}

	private void storySelection() {
		if (settings.getLastStory() != null) {
			story = settings.getLastStory();
			startStory(story);

		} else {
			showStoryManger();
		}

	}

	private void startStory(String s) {
		story = s;
		storyPath = homePath + "/StoryLine/" + story;
		dbFile = storyPath + "/database/" + story + ".db";
		loadActiveStory();
		loadChapters();
		loadCharacters();
		loadFactions();
		loadLocs();
		loadNotes();
		loadPlots();
		buildTree();
		showStory();
	}

	private void localizeUI() {
		// TODO localize the UI

	}

	public void addActionListners() {

		// Menu
		StoryLineAppGUI.mntmExit.addActionListener(this);
		StoryLineAppGUI.mntmManageStories.addActionListener(this);
		StoryLineAppGUI.mntmAuthor.addActionListener(this);
		StoryLineAppGUI.mntmSettings.addActionListener(this);

		// author
		
		// Details
		AppDetailsNote.btnNoteCreate.addActionListener(this);
		AppDetailsNote.btnNoteDelete.addActionListener(this);
		// story
		AppPanelStory.btnStoryCreate.addActionListener(this);
		AppPanelStory.btnStoryDelete.addActionListener(this);
		AppPanelStory.btnStoryEdit.addActionListener(this);
		// story manager
		AppPanelStoryManager.btnDeleteStory.addActionListener(this);
		AppPanelStoryManager.btnNewStory.addActionListener(this);
		AppPanelStoryManager.btnOpenStory.addActionListener(this);
		// chapter overview
		AppPanelChapterOverview.btnChapterCreate.addActionListener(this);
		AppPanelChapterOverview.btnChapterDelete.addActionListener(this);
		AppPanelChapterOverview.btnChapterEdit.addActionListener(this);
		AppPanelChapterOverview.btnNrDown.addActionListener(this);
		AppPanelChapterOverview.btnNrUp.addActionListener(this);
		// chapter
		AppPanelChapter.btnChapterCreate.addActionListener(this);
		AppPanelChapter.btnChapterDelete.addActionListener(this);
		AppPanelChapter.btnChapterEdit.addActionListener(this);
		AppPanelChapter.btnChapterNrDown.addActionListener(this);
		AppPanelChapter.btnChapterNrUp.addActionListener(this);
		// scene overview
		AppPanelSceneOverview.btnNrDown.addActionListener(this);
		AppPanelSceneOverview.btnNrUp.addActionListener(this);
		AppPanelSceneOverview.btnSceneCreate.addActionListener(this);
		AppPanelSceneOverview.btnSceneDelete.addActionListener(this);
		AppPanelSceneOverview.btnSceneEdit.addActionListener(this);
		// scene
		AppPanelScene.btnSceneAddAllChars.addActionListener(this);
		AppPanelScene.btnSceneAddChar.addActionListener(this);
		AppPanelScene.btnSceneCreate.addActionListener(this);
		AppPanelScene.btnSceneDelete.addActionListener(this);
		AppPanelScene.btnSceneEdit.addActionListener(this);
		AppPanelScene.btnSceneFile.addActionListener(this);
		AppPanelScene.btnSceneNrDown.addActionListener(this);
		AppPanelScene.btnSceneNrUp.addActionListener(this);
		AppPanelScene.btnSceneRemoveAllChars.addActionListener(this);
		AppPanelScene.btnSceneRemoveChar.addActionListener(this);
		// character overview
		AppPanelCharacterOverview.btnCharOverviewCreate.addActionListener(this);
		AppPanelCharacterOverview.btnCharOverviewDelete.addActionListener(this);
		AppPanelCharacterOverview.btnCharOverviewEdit.addActionListener(this);
		// character
		AppPanelCharacter.btnCharCreate.addActionListener(this);
		AppPanelCharacter.btnCharDelete.addActionListener(this);
		AppPanelCharacter.btnCharEdit.addActionListener(this);
		AppPanelCharacter.btnCharImage.addActionListener(this);
		// location overview
		AppPanelLocationOverview.btnLocOverviewCreate.addActionListener(this);
		AppPanelLocationOverview.btnLocOverviewDelete.addActionListener(this);
		AppPanelLocationOverview.btnLocOverviewEdit.addActionListener(this);
		// location
		AppPanelLocation.btnChapterCreate.addActionListener(this);
		AppPanelLocation.btnChapterDelete.addActionListener(this);
		AppPanelLocation.btnChapterEdit.addActionListener(this);
		AppPanelLocation.btnLocImage.addActionListener(this);
		AppPanelLocation.btnLocMap.addActionListener(this);
		AppPanelLocation.btnLocWeb.addActionListener(this);
		// faction overview
		AppPanelFactionOverview.btnFactionOverviewCreate
				.addActionListener(this);
		AppPanelFactionOverview.btnFactionOverviewDelete
				.addActionListener(this);
		AppPanelFactionOverview.btnFactionOverviewEdit.addActionListener(this);
		// faction
		AppPanelFaction.btnChapterCreate.addActionListener(this);
		AppPanelFaction.btnChapterDelete.addActionListener(this);
		AppPanelFaction.btnChapterEdit.addActionListener(this);
		// plot overview
		AppPanelPlotOverview.btnPlotOverviewCreate.addActionListener(this);
		AppPanelPlotOverview.btnPlotOverviewDelete.addActionListener(this);
		AppPanelPlotOverview.btnPlotOverviewEdit.addActionListener(this);
		// plot
		AppPanelPlot.btnPlotCreate.addActionListener(this);
		AppPanelPlot.btnPlotDelete.addActionListener(this);
		AppPanelPlot.btnPlotEdit.addActionListener(this);
	}

	// this reacts to a selection event on our tree
	// and parses through the selection to determine what to do

	@Override
	public void actionPerformed(ActionEvent e) {

		if (e.getSource() == StoryLineAppGUI.mntmExit) {
			System.exit(-1);
		}
		if (e.getSource() == StoryLineAppGUI.mntmSettings){
			showSettings();
		}
		if (e.getSource() == StoryLineAppGUI.mntmManageStories) {
			showStoryManger();
		}
		if (e.getSource() == StoryLineAppGUI.mntmAuthor){
			showAuthor();
		}

		if (e.getSource() == AppPanelStory.btnStoryCreate) {
			createStory();
			showStoryManger();
		}
		if (e.getSource() == AppPanelStory.btnStoryEdit) {
			editStory();
		}
		if (e.getSource() == AppPanelStory.btnStoryDelete) {
			int n = JOptionPane.showConfirmDialog(panelLocacionOverview,
					"Do you really want to delete this?", "Warning",
					JOptionPane.OK_CANCEL_OPTION);
			if (n == JOptionPane.YES_OPTION) {
				deleteStory();
				showStoryManger();
			}

		}
		if (e.getSource() == AppDetailsNote.btnNoteDelete) {
			deleteNote();
		}
		if (e.getSource() == AppDetailsNote.btnNoteCreate) {
			createNote();
		}

		if (e.getSource() == AppPanelStoryManager.btnDeleteStory) {
			deleteStory();
		}
		if (e.getSource() == AppPanelStoryManager.btnNewStory) {
			createStory();
		}
		if (e.getSource() == AppPanelStoryManager.btnOpenStory) {
			openStory();
		}
		if (e.getSource() == AppPanelChapter.btnChapterCreate) {
			createChapterPanel();
			expandChapters();
		}
		if (e.getSource() == AppPanelChapter.btnChapterDelete) {
			deleteChapter();
			expandChapters();
		}
		if (e.getSource() == AppPanelChapter.btnChapterEdit) {
			editChapter();
			showChapter(selectedChapter);
			expandChapters();
		}
		if (e.getSource() == AppPanelChapter.btnChapterNrDown) {
			chapterNrDown();
			expandChapters();
		}
		if (e.getSource() == AppPanelChapter.btnChapterNrUp) {
			chapterNrUp();
			expandChapters();
		}
		if (e.getSource() == AppPanelChapterOverview.btnNrDown) {
			selectedChapter = (Chapter) chapterList.getElementAt(listChapters
					.getSelectedIndex());
			chapterNrDown();
			showChapterOverview();
			expandChapters();
		}
		if (e.getSource() == AppPanelChapterOverview.btnNrUp) {
			selectedChapter = (Chapter) chapterList.getElementAt(listChapters
					.getSelectedIndex());
			chapterNrUp();
			showChapterOverview();
			expandChapters();
		}
		if (e.getSource() == AppPanelChapterOverview.btnChapterCreate) {
			createChapterOverview();
			showChapterOverview();
			expandChapters();
		}
		if (e.getSource() == AppPanelChapterOverview.btnChapterDelete) {
			deleteChapterOverview();
			expandChapters();
		}
		if (e.getSource() == AppPanelChapterOverview.btnChapterEdit) {
			editChapterOverview();
			expandChapters();
		}
		if (e.getSource() == AppPanelSceneOverview.btnSceneCreate) {
			createSceneOverview();
			showScenesOverview();
			expandChapters();
			expandScenes();
		}
		if (e.getSource() == AppPanelSceneOverview.btnSceneEdit) {
			editSceneOverview();
			expandChapters();
			expandScenes();
		}
		if (e.getSource() == AppPanelSceneOverview.btnSceneDelete) {
			deleteSceneOverview();
			expandChapters();
			expandScenes();
		}
		if (e.getSource() == AppPanelSceneOverview.btnNrUp) {
			selectedScene = (Scene) sceneList.getElementAt(listScenes
					.getSelectedIndex());
			sceneNrUp();
			showScenesOverview();
			expandChapters();
			expandScenes();
		}
		if (e.getSource() == AppPanelSceneOverview.btnNrDown) {
			selectedScene = (Scene) sceneList.getElementAt(listScenes
					.getSelectedIndex());
			sceneNrDown();
			showScenesOverview();
			expandChapters();
			expandScenes();
		}
		if (e.getSource() == AppPanelScene.btnSceneCreate) {
			createScenePanel();
			expandChapters();
			expandScenes();
		}
		if (e.getSource() == AppPanelScene.btnSceneDelete) {
			deleteScene();
			expandChapters();
			expandScenes();
		}
		if (e.getSource() == AppPanelScene.btnSceneEdit) {
			editScene();
			expandChapters();
			expandScenes();
		}
		if (e.getSource() == AppPanelScene.btnSceneAddAllChars) {
			addAllCharsToScene();
		}
		if (e.getSource() == AppPanelScene.btnSceneAddChar) {
			addCharsToScene();
		}
		if (e.getSource() == AppPanelScene.btnSceneRemoveAllChars) {
			removeAllCharsFromScene();
		}
		if (e.getSource() == AppPanelScene.btnSceneRemoveChar) {
			removeCharFromScene();
		}
		if (e.getSource() == AppPanelScene.btnSceneFile) {
			dialogSceneFile();
		}
		if (e.getSource() == AppPanelScene.btnSceneNrDown) {
			sceneNrDown();
			showScenes(selectedScene);
			expandChapters();
			expandScenes();
		}
		if (e.getSource() == AppPanelScene.btnSceneNrUp) {
			sceneNrUp();
			showScenes(selectedScene);
			expandChapters();
			expandScenes();
		}
		if (e.getSource() == AppPanelCharacterOverview.btnCharOverviewCreate) {
			createCharacterOverview();
			showCharacterOverview();
			expandCharacters();
		}
		if (e.getSource() == AppPanelCharacterOverview.btnCharOverviewDelete) {
			deleteCharacterOverview();
			showCharacterOverview();
			expandCharacters();
		}
		if (e.getSource() == AppPanelCharacterOverview.btnCharOverviewEdit) {
			showCharacter(selectedCharacter);
			expandCharacters();
		}
		if (e.getSource() == AppPanelCharacter.btnCharCreate) {

			createCharacterPanel();
			expandCharacters();
		}
		if (e.getSource() == AppPanelCharacter.btnCharDelete) {
			deleteCharacter(selectedCharacter);
			expandCharacters();
		}
		if (e.getSource() == AppPanelCharacter.btnCharEdit) {
			editCharacter();
			expandCharacters();
		}
		if (e.getSource() == AppPanelCharacter.btnCharImage) {
			selectCharImage();
			expandCharacters();
		}
		if (e.getSource() == AppPanelLocationOverview.btnLocOverviewCreate) {
			createLocationOverview();
			expandLocations();
		}
		if (e.getSource() == AppPanelLocationOverview.btnLocOverviewDelete) {
			deleteLocationOverview();
			expandLocations();
		}
		if (e.getSource() == AppPanelLocationOverview.btnLocOverviewEdit) {
			editLocationOverview();
			expandLocations();
		}
		if (e.getSource() == AppPanelLocation.btnChapterCreate) {
			createLocationPanel();
			expandLocations();
		}
		if (e.getSource() == AppPanelLocation.btnChapterDelete) {
			deleteLocationPanel();
			expandLocations();
		}
		if (e.getSource() == AppPanelLocation.btnChapterEdit) {
			editLocation();
			expandLocations();
		}
		if (e.getSource() == AppPanelLocation.btnLocImage) {
			selectLocImage();
			expandLocations();
		}
		if (e.getSource() == AppPanelLocation.btnLocMap) {
			//addMapToLocation();
			expandLocations();
		}
		if (e.getSource() == AppPanelLocation.btnLocWeb) {
			showWebLink();
			expandLocations();
		}
		if (e.getSource() == AppPanelFactionOverview.btnFactionOverviewCreate) {
			createFactionOverview();
			expandFactions();
		}
		if (e.getSource() == AppPanelFactionOverview.btnFactionOverviewDelete) {
			deleteFactionOverview();
			expandFactions();
		}
		if (e.getSource() == AppPanelFactionOverview.btnFactionOverviewEdit) {
			editFactionOverview();
			expandFactions();
		}
		if (e.getSource() == AppPanelFaction.btnChapterCreate) {
			createFactionPanel();
			expandFactions();
		}
		if (e.getSource() == AppPanelFaction.btnChapterDelete) {
			deleteFactionPanel();
			expandFactions();
		}
		if (e.getSource() == AppPanelFaction.btnChapterEdit) {
			editFaction();
			expandFactions();
		}
		if (e.getSource() == AppPanelPlotOverview.btnPlotOverviewCreate) {
			createPlotOverview();
			expandPlots();
		}
		if (e.getSource() == AppPanelPlotOverview.btnPlotOverviewDelete) {
			deletePlotOverview();
			expandPlots();
		}
		if (e.getSource() == AppPanelPlotOverview.btnPlotOverviewEdit) {
			editPlotOverview();
			expandPlots();
		}
		if (e.getSource() == AppPanelPlot.btnPlotCreate) {
			createPlotPanel();
			expandPlots();
		}
		if (e.getSource() == AppPanelPlot.btnPlotDelete) {
			deletePlotPanel();
			expandPlots();
		}
		if (e.getSource() == AppPanelPlot.btnPlotEdit) {
			editPlot();
			expandPlots();
		}
	}

	private void showSettings() {
		Object[] message = { new AppPanelSettings() };
		JOptionPane pane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE,
				JOptionPane.DEFAULT_OPTION);
		pane.createDialog(null, "Author").setVisible(true);
	}

	private void showAuthor() {
		System.out.println(activeStory.toString() + StoryAuthor);
		
		disableMenuItems();
		clearDetails();
		showDetails();
		disableMenuItems();
		StoryLineAppGUI.panelContent.removeAll();
		StoryLineAppGUI.panelContent.repaint();
		StoryLineAppGUI.panelContent.add(panelAuthor);
		StoryLineAppGUI.lblStatusOutput.setText("author settings");

	}

	private void showWebLink() {
		String url = AppPanelLocation.txtLocWeb.getText();
	    try {
			java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	  }

	private void editStory() {
		Story tmp = new Story();
		tmp.setStoryAuthor(activeStory.getStoryAuthor());
		tmp.setDescription(AppPanelStory.editorDesc.getText());
		tmp.setName(AppPanelStory.txtStoryName.getText());
		activeStory.dbEditStory(dbFile, tmp);
		clearData();
		startStory(story);

	}

	private void createNote() {

		Note t = new Note();
		NotePanel panel = new NotePanel();
		
		Object[] message = { panel };
		JOptionPane pane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE,
				JOptionPane.OK_CANCEL_OPTION);
		pane.createDialog(null, "edit note").setVisible(true);

		if (NotePanel.txtTitle.getText().equals("") | NotePanel.txtContent.getText().equals("")) {
			System.out.println("notetitle and content required");
			return;
		}
		t.setName(NotePanel.txtTitle.getText());
		t.setContent("<html>" + NotePanel.txtContent.getText() +"</html>");
		NotePanel.txtContent.setText("");
		NotePanel.txtTitle.setText("");
		activeNotes.add(t);
		t.dbCreateNote(dbFile);
		showDetails();

	}

	private void deleteNote() {

		int n = JOptionPane.showConfirmDialog(panelLocacionOverview,
				"Do you really want to delete this?", "Warning",
				JOptionPane.OK_CANCEL_OPTION);
		if (n == JOptionPane.YES_OPTION) {
			selectedNote = (Note) listNotes.getSelectedValue();
			selectedNote.dbDeleteNote(dbFile);
			activeNotes.remove(selectedNote);
			AppDetailsNote.txtDesc.setText("");
			showDetails();
		}

	}

	private void openStory() {
		try {
			story = (String) listStory.getSelectedValue();
			settings.updateStory(story);
			clearData();
			startStory(story);
		} catch (com.db4o.ext.Db4oIOException e) {
			StoryLineAppGUI.lblStatusOutput.setText("nothing selected");
		}

	}

	private void clearData() {
		activeChapters = new ArrayList<Chapter>();
		activeCharacters = new ArrayList<Character>();
		activeFactions = new ArrayList<Faction>();
		activeLocations = new ArrayList<Location>();
		activeNotes = new ArrayList<Note>();
		activePlots = new ArrayList<Plot>();
		activeStory = new Story();

	}

	private void createStory() {
		String input = JOptionPane.showInputDialog(null,
				"Enter a name for your story:", "Create a new story",
				JOptionPane.PLAIN_MESSAGE);
		StoryLineAppGUI.lblStatusOutput.setText("create new story: " + input);
		if (input == null) {
			return;
		}

		File folder = new File(homePath, "StoryLine");
		if (folder.exists()) {
			System.out.println("folder exists");
		} else {
			folder.mkdir();
		}
		File project = new File(folder, input);
		if (project.exists()) {
			System.out.println("config exists");
		} else {
			project.mkdir();
		}
		for (int i = 0; i < folders.length; i++) {
			String f = folders[i];
			File tmp = new File(project, f);
			if (!tmp.exists()) {
				tmp.mkdir();
			}
		}
		File tmpdb = new File(project, "database" + "/" + input + ".db");
		try {
			tmpdb.createNewFile();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		new application.InitDBedit(tmpdb.toString(), input);
		// storyList.addElement(input);
		storyList.addElement(input);
		Settings tmp = new Settings();
		tmp.setLastStory(input);
		tmp.setStories(settings.getStories());
		tmp.stories.add(input);
		settings.update(tmp);

	}

	private void deleteStory() {
		story = "";
		story = (String) listStory.getSelectedValue();
		try {
			int n = JOptionPane.showConfirmDialog(panelLocacionOverview,
					"Delete this story: " + story + "?", "Warning",
					JOptionPane.OK_CANCEL_OPTION);
			if (n == JOptionPane.YES_OPTION) {
				File folder = new File(homePath, "StoryLine");
				File project = new File(folder, story);
				if (project.exists()) {
					project.delete();
					deleteProject(project);
				}
				storyList.removeElement(story);
				Settings tmp = new Settings();
				tmp.setLastStory(null);
				tmp.setStories(settings.getStories());
				tmp.stories.remove(story);
				;
				settings.update(tmp);
			}
		} catch (NullPointerException e) {
			StoryLineAppGUI.lblStatusOutput.setText("nothing selected");
		}

	}

	private void deleteProject(File project) {

		File tmp = project;
		File[] files = tmp.listFiles();
		for (int i = 0; i < files.length; i++) {
			File f = files[i];
			if (f.isDirectory() == true) {
				File[] ff = f.listFiles();
				for (int j = 0; j < ff.length; j++) {
					File del = ff[j];
					del.delete();
				}
				f.delete();
			} else {
				f.delete();
			}
		}
		project.delete();

	}

	@Override
	public void valueChanged(TreeSelectionEvent e) {

		path = e.getPath();
		elements = path.getPath();
		int l = elements.length;
		path.getLastPathComponent().toString();
		AppPanelChapterOverview.lblChapterNr.setVisible(true);

		// circle through the path of the selection to identify the selected
		// object
		for (int i = 0; i < elements.length; i++) {
			String a = elements[i].toString();
			Object thiselement = path.getLastPathComponent();
			String te = thiselement.toString();

			if (te == activeStory.toString()) {
				showStory();
			}
			// is it chapterOvewview?
			if (a == "Chapters") {
				showChapterOverview();
				disableChapterButtons();

				// is it a chapter?
				if (l == 3) {
					treeSelectedItem = te;
					whatChapter();
					showChapter(selectedChapter);

				}
				if (l == 4) {
					showScenesOverview();
				}
				if (l == 5) {
					treeSelectedItem = te;
					showScenes(selectedScene);

				}
			} else if (a == "Characters") {
				showCharacterOverview();
			}
			if (a == "Main Cast") {
				showCharacterOverview();
				if (l == 4) {
					treeSelectedItem = te;
					for (int j = 0; j < activeCharacters.size(); j++) {
						Character t = activeCharacters.get(j);
						if (t.toString().equals(te)) {
							selectedCharacter = t;
						}

					}
					showCharacter(selectedCharacter);

				}
			} else if (a == "Support Cast") {
				showCharacterOverview();
				showDetails();
				if (l == 4) {
					treeSelectedItem = te;
					for (int j = 0; j < activeCharacters.size(); j++) {
						Character t = activeCharacters.get(j);
						if (t.toString().equals(te)) {
							selectedCharacter = t;
						}

					}
					showCharacter(selectedCharacter);

				}
			} else if (a == "Extras") {
				showCharacterOverview();
				showDetails();
				if (l == 4) {
					treeSelectedItem = te;
					for (int j = 0; j < activeCharacters.size(); j++) {
						Character t = activeCharacters.get(j);
						if (t.toString().equals(te)) {
							selectedCharacter = t;
						}

					}
					showCharacter(selectedCharacter);

				}
			} else if (a == "Locations") {
				showLocationOverview();
				if (l == 3) {
					treeSelectedItem = te;
					showLocation(selectedLocation);
				}
			} else if (a == "Factions") {
				showFactionOverview();
				if (l == 3) {
					treeSelectedItem = te;
					showFaction(selectedFaction);
				}
			} else if (a == "Plots") {
				showPlotOverview();
				if (l == 3) {
					treeSelectedItem = te;
					showPlot(selectedPlot);
				}
			}

		}
		StoryLineAppGUI.lblStatusOutput.setText(path.toString());

	}

	private void showDetails() {
		StoryLineAppGUI.panelSide.removeAll();
		AppDetailsNote.txtDesc.setVisible(true);
		AppDetailsNote.imagePanel.setVisible(false);
		StoryLineAppGUI.panelSide.add(detailsNote);
		AppDetailsNote.txtDesc.setBackground(UIManager.getColor("Button.background"));

		noteList = new DefaultListModel();
		listNotes = new JList(noteList);
		listNotes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listNotes.addListSelectionListener(this);
		listNotes.setBorder(null);
		AppDetailsNote.scrollNoteList.setViewportView(listNotes);
		ArrayList<Note> notes = activeNotes;
		for (int i = 0; i < notes.size(); i++) {
			noteList.addElement(notes.get(i));
		}
		StoryLineAppGUI.panelSide.repaint();
	}

	@Override
	public void valueChanged(ListSelectionEvent e) {
		// TODO Auto-generated method stub
		if (e.getSource() == listNotes) {
			for (int i = 0; i < activeNotes.size(); i++) {
				Note t = activeNotes.get(i);
				if (t.equals(listNotes.getSelectedValue())) {
					selectedNote = t;
				}
			}AppDetailsNote.txtDesc.setVisible(true);
			AppDetailsNote.txtDesc.setContentType("text/html");
			AppDetailsNote.txtDesc.setText(selectedNote.getContent());

			int w=AppDetailsNote.scrollPane.getWidth()-15;
			int h=AppDetailsNote.scrollPane.getHeight();
			AppDetailsNote.txtDesc.setBounds(0, 0, w, h);
			AppDetailsNote.txtDesc.repaint();
			AppDetailsNote.txtDesc.setCaretPosition(0);
			
			
		}
		if (e.getSource() == listPlotScenes) {
			Scene c = (Scene) plotSceneList.getElementAt(listPlotScenes
					.getSelectedIndex());
			for (int i = 0; i < activeChapters.size(); i++) {
				Chapter chap = activeChapters.get(i);
				for (int j = 0; j < chap.scenes.size(); j++) {
					Scene sc = chap.scenes.get(j);
					if (c.equals(sc.toString())) {
						selectedChapter = chap;
						selectedScene = sc;
					}
				}
			}
			AppPanelSceneOverview.lblSceneNr
					.setText("" + selectedScene.getNr());
		}
		if (e.getSource() == listScenes) {
			Scene c = (Scene) sceneList.getElementAt(listScenes
					.getSelectedIndex());
			for (int i = 0; i < activeChapters.size(); i++) {
				Chapter chap = activeChapters.get(i);
				for (int j = 0; j < chap.scenes.size(); j++) {
					Scene sc = chap.scenes.get(j);
					if (c.equals(sc.toString())) {
						selectedChapter = chap;
						selectedScene = sc;
					}
				}
			}
			AppPanelSceneOverview.lblSceneNr
					.setText("" + selectedScene.getNr());
		}
		if (e.getSource() == listChapters) {
			Chapter strCh = (Chapter) chapterList.getElementAt(listChapters
					.getSelectedIndex());
			for (int i = 0; i < activeChapters.size(); i++) {
				Chapter chap = activeChapters.get(i);
				for (int j = 0; j < chap.scenes.size(); j++) {
					Scene sc = chap.scenes.get(j);
					if (strCh.equals(sc.toString())) {
						selectedChapter = chap;
						selectedScene = sc;
					}
				}
			}
			AppPanelChapterOverview.lblChapterNr.setText(""
					+ selectedChapter.getNr());
		}
		if (e.getSource() == listChars) {
			try {
				for (int i = 0; i < activeCharacters.size(); i++) {
					Object s = listChars.getSelectedValue();
					if (s.toString().equals(activeCharacters.get(i).toString())) {
						selectedCharacter = activeCharacters.get(i);
					}
				}
			} catch (NullPointerException ex) {

			}
		}
	}

	public void buildUI() {
		disableMenuItems();
		StoryLineAppGUI.panelSide.setVisible(true);
		showStory();
		showDetails();
	}


	private void showStoryManger() {
		disableMenuItems();
		clearDetails();
		showDetails();
		StoryLineAppGUI.panelContent.removeAll();
		StoryLineAppGUI.panelContent.repaint();
		StoryLineAppGUI.panelContent.add(panelStoryManager);
		storyList = new DefaultListModel();
		listStory = new JList(storyList);
		listStory.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listStory.addListSelectionListener(this);
		AppPanelStoryManager.scrollPane.setViewportView(listStory);
		for (int i = 0; i < settings.stories.size(); i++) {
			String t = settings.stories.get(i);
			storyList.addElement(t);
		}
		StoryLineAppGUI.lblStatusOutput.setText(story);

	}

	public void disableMenuItems() {
		StoryLineAppGUI.mnChapter.setVisible(false);
		StoryLineAppGUI.mnScene.setVisible(false);
		StoryLineAppGUI.mnCharacter.setVisible(false);
		StoryLineAppGUI.mnLocation.setVisible(false);
		StoryLineAppGUI.mnFaction.setVisible(false);
		StoryLineAppGUI.mnPlot.setVisible(false);
	}

	// these functions show the panels for the selection
	public void showStory() {
		showDetails();
		disableMenuItems();
		StoryLineAppGUI.panelContent.removeAll();
		StoryLineAppGUI.panelContent.repaint();
		StoryLineAppGUI.panelContent.add(panelStory);
		StoryLineAppGUI.panelSide.removeAll();
		
		AppDetailsNote.txtDesc.setText("");
		AppDetailsNote.imagePanel.removeAll();

		
		showDetails();
		AppPanelStory.txtStoryName.setText(activeStory.getName());
		AppPanelStory.editorDesc.setText(activeStory.getDescription());
		// TODO: generate Story details

	}

	public void whatChapter() {
		ArrayList<Chapter> chapters = activeChapters;
		for (int i = 0; i < chapters.size(); i++) {
			Chapter tmp = chapters.get(i);
			if (tmp.toString().equals(treeSelectedItem)) {
				selectedChapter = tmp;
			}
		}
	}

	public void showChapter(Chapter c) {
		selectedChapter = c;
		showDetails();
		disableMenuItems();
		StoryLineAppGUI.mnChapter.setVisible(true);
		StoryLineAppGUI.panelContent.removeAll();
		StoryLineAppGUI.panelContent.repaint();
		StoryLineAppGUI.panelContent.add(panelChapter);
		AppPanelChapter.btnChapterEdit.setText("Save");
		AppPanelChapter.lblActChapterNr.setText("Nr: "
				+ selectedChapter.getNr());
		AppPanelChapter.txtChapterName.setText(selectedChapter.getName());
		AppPanelChapter.editorChapterDesc.setText(selectedChapter
				.getDescription());

	}

	public void showChapterOverview() {
		showDetails();
		disableMenuItems();
		StoryLineAppGUI.mnChapter.setVisible(true);
		StoryLineAppGUI.panelContent.removeAll();
		StoryLineAppGUI.panelContent.repaint();
		StoryLineAppGUI.panelContent.add(panelChapterOverview);
		chapterList = new DefaultListModel();
		listChapters = new JList(chapterList);
		listChapters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listChapters.addListSelectionListener(this);
		AppPanelChapterOverview.scrollPane.setViewportView(listChapters);
		ArrayList<Chapter> chapters = activeChapters;
		for (int i = 0; i < chapters.size(); i++) {
			chapterList.addElement(chapters.get(i));
		}
	}

	public void whatScene() {
		elements = path.getPath();
		String strScene = path.getLastPathComponent().toString();
		String strChapter = path.getPathComponent(2).toString();
		ArrayList<Chapter> tmpChapters = activeChapters;
		for (int i = 0; i < tmpChapters.size(); i++) {
			Chapter tmp = tmpChapters.get(i);
			if (strChapter.equals(tmp.toString())) {
				selectedChapter = tmp;
			}
		}
		ArrayList<Scene> tmpScenes = selectedChapter.getScenes();
		for (int j = 0; j < tmpScenes.size(); j++) {
			Scene tmp = tmpScenes.get(j);
			if (strScene.equals(tmp.toString())) {
				selectedScene = tmp;
			}
		}
	}

	public void showScenes(Scene c) {

		selectedScene = c;
		whatScene();
		showDetails();
		disableMenuItems();
		StoryLineAppGUI.mnScene.setVisible(true);
		StoryLineAppGUI.panelContent.removeAll();
		AppPanelScene.dropSceneStatus.removeAllItems();
		AppPanelScene.dropSceneLocation.removeAllItems();
		AppPanelScene.dropScenePlot.removeAllItems();
		AppPanelScene.dropSceneChapter.removeAllItems();
		StoryLineAppGUI.panelContent.repaint();
		StoryLineAppGUI.panelContent.add(panelScene);
		AppPanelScene.btnSceneEdit.setText("Save");
		// set text
		AppPanelScene.lblSceneActNr.setText("Nr: " + selectedScene.getNr());
		AppPanelScene.txtSceneName.setText(selectedScene.getName());
		AppPanelScene.taSceneDesc.setText(selectedScene.getDescription());
		AppPanelScene.txtSceneMonth.setText(selectedScene.getDate().substring(
				0, 2));
		AppPanelScene.txtSceneDay.setText(selectedScene.getDate().substring(3,
				5));
		AppPanelScene.txtSceneYear.setText(selectedScene.getDate().substring(6,
				10));
		// get the lists right
		allCharsList = new DefaultListModel();
		listAllChars = new JList(allCharsList);
		listAllChars.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listAllChars.addListSelectionListener(this);
		AppPanelScene.scrollSceneAvailableChars.setViewportView(listAllChars);
		ArrayList<Character> allcharacters = activeCharacters;
		for (int i = 0; i < allcharacters.size(); i++) {
			Character tmp = allcharacters.get(i);
			if (selectedScene.characters.contains(tmp.toString()) == false) {
				allCharsList.addElement(tmp);
			}

		}
		selCharsList = new DefaultListModel();
		listSelChars = new JList(selCharsList);
		listSelChars.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listSelChars.addListSelectionListener(this);
		AppPanelScene.scrollSceneSelectedChars.setViewportView(listSelChars);
		ArrayList<String> selcharacters = selectedScene.getCharacters();
		for (int i = 0; i < selcharacters.size(); i++) {
			String tmp = selcharacters.get(i);
			if (selcharacters.size() > 0) {
				selCharsList.addElement(tmp);
			}
		}

		AppPanelScene.txtSceneDuration.setText(selectedScene.getDuration());
		AppPanelScene.txtSceneFile.setText(selectedScene.getFile());
		ArrayList<Location> alllocations = activeLocations;
		ArrayList<Plot> allplots = activePlots;
		for (int i = 0; i < alllocations.size(); i++) {
			Location tmp = alllocations.get(i);
			if (alllocations.size() > 0) {
				AppPanelScene.dropSceneLocation.addItem(tmp);
			}
		}
		int a = AppPanelScene.dropSceneLocation.getItemCount();
		for (int i = 0; i < a; i++) {
			Object tmp = AppPanelScene.dropSceneLocation.getItemAt(i);
			String tmpLoc = selectedScene.getLocation();
			if (tmp.toString().equals(tmpLoc.toString())) {

				for (int j = 0; j < activeLocations.size(); j++) {
					Location l = activeLocations.get(j);
					if (l.toString().equals(tmpLoc))
						;
					selectedLocation = l;
					AppPanelScene.dropSceneLocation.setSelectedIndex(i);
				}

			}
		}
		for (int i = 0; i < allplots.size(); i++) {
			Plot tmp = allplots.get(i);
			if (allplots.size() > 0) {
				AppPanelScene.dropScenePlot.addItem(tmp);
			}
		}
		ArrayList<Plot> plots = activePlots;
		int b = plots.size();
		for (int i = 0; i < b; i++) {
			Plot tmp = plots.get(i);
			ArrayList<String> scenesinplot = tmp.getScenes();
			int t = scenesinplot.size();
			for (int j = 0; j < t; j++) {
				String tmpScene = scenesinplot.get(j);
				if (tmpScene.toString().equals(selectedScene.toString())) {
					selectedPlot = tmp;
				}
			}
		}
		a = AppPanelScene.dropScenePlot.getItemCount();
		for (int i = 0; i < a; i++) {
			Plot tmp = (Plot) AppPanelScene.dropScenePlot.getItemAt(i);
			if (selectedPlot.toString().equals(tmp.toString())) {
				AppPanelScene.dropScenePlot.setSelectedIndex(i);
			}
		}
		for (int i = 0; i < SceneStatus.length; i++) {
			AppPanelScene.dropSceneStatus.addItem(SceneStatus[i]);
		}
		for (int i = 0; i < AppPanelScene.dropSceneStatus.getItemCount(); i++) {
			Object s = AppPanelScene.dropSceneStatus.getItemAt(i);
			String t = selectedScene.getStatus();
			if (s.toString().equals(t)) {
				AppPanelScene.dropSceneStatus.setSelectedIndex(i);
			}
		}
		ArrayList<Chapter> chapters = activeChapters;
		for (int i = 0; i < chapters.size(); i++) {
			AppPanelScene.dropSceneChapter.addItem(chapters.get(i).getNr());
		}
	}

	public void showScenesOverview() {
		whatScene();
		showDetails();
		disableMenuItems();
		StoryLineAppGUI.mnScene.setVisible(true);
		StoryLineAppGUI.panelContent.removeAll();
		StoryLineAppGUI.panelContent.repaint();
		StoryLineAppGUI.panelContent.add(panelSceneOverview);
		sceneList = new DefaultListModel();
		listScenes = new JList(sceneList);
		listScenes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listScenes.addListSelectionListener(this);
		AppPanelSceneOverview.scrollPane.setViewportView(listScenes);
		ArrayList<Scene> scenes = selectedChapter.getScenes();
		for (int i = 0; i < scenes.size(); i++) {
			sceneList.addElement(scenes.get(i));
		}
	}

	public void whatCharacter() {
		String s = path.getLastPathComponent().toString();
		if (s != null) {
			ArrayList<Character> characters = activeCharacters;
			for (int i = 0; i < characters.size(); i++) {
				Character tmp = characters.get(i);
				if (tmp.toString().equals(s)) {
					selectedCharacter = tmp;
				}
			}
		}
	}

	public void showCharacter(Character c) {
		if (listChars.isSelectionEmpty() == false) {
			whatCharacter();
		}
		selectedCharacter = c;
		showDetails();
		disableMenuItems();
		StoryLineAppGUI.mnCharacter.setVisible(true);
		StoryLineAppGUI.panelContent.removeAll();
		AppPanelCharacter.dropCharFaction.removeAllItems();
		AppPanelCharacter.dropCharLevel.removeAllItems();
		AppPanelCharacter.dropCharRole.removeAllItems();
		AppPanelCharacter.dropGender.removeAllItems();
		StoryLineAppGUI.panelContent.repaint();
		StoryLineAppGUI.panelContent.add(panelCharacter);
		AppPanelCharacter.txtCharAge.setText(selectedCharacter.getAge());
		AppPanelCharacter.txtFirstname
				.setText(selectedCharacter.getFirstName());
		AppPanelCharacter.txtImageUrl.setText(selectedCharacter.getImage());
		AppPanelCharacter.txtName.setText(selectedCharacter.getName());
		AppPanelCharacter.txtNickname.setText(selectedCharacter.getNickName());
		AppPanelCharacter.taCharDesc
				.setText(selectedCharacter.getDescription());

		for (int i = 0; i < Gender.length; i++) {
			AppPanelCharacter.dropGender.addItem(Gender[i]);
			if (selectedCharacter.getGender().equals(Gender[i])) {
				AppPanelCharacter.dropGender.setSelectedIndex(i);
			}
		}

		for (int i = 0; i < Roles.length; i++) {
			AppPanelCharacter.dropCharRole.addItem(Roles[i]);
		}
		for (int i = 0; i < AppPanelCharacter.dropCharRole.getItemCount(); i++) {
			Object o = AppPanelCharacter.dropCharRole.getItemAt(i);
			String s = selectedCharacter.getRole();
			if (o.toString().equals(s)) {
				AppPanelCharacter.dropCharRole.setSelectedIndex(i);
			}
		}
		for (int i = 0; i < Level.length; i++) {
			AppPanelCharacter.dropCharLevel.addItem(Level[i]);
		}
		for (int i = 0; i < AppPanelCharacter.dropCharLevel.getItemCount(); i++) {
			Object o = AppPanelCharacter.dropCharLevel.getItemAt(i);
			String s = selectedCharacter.getLevel();
			if (o.toString().equals(s)) {
				AppPanelCharacter.dropCharLevel.setSelectedIndex(i);
			}
		}
		ArrayList<Faction> factions = activeFactions;
		for (int i = 0; i < factions.size(); i++) {
			Faction tmp = factions.get(i);
			AppPanelCharacter.dropCharFaction.addItem(tmp);
		}
		try {
			for (int i = 0; i < AppPanelCharacter.dropCharFaction
					.getItemCount(); i++) {
				Object o = AppPanelCharacter.dropCharFaction.getItemAt(i);
				Object s = selectedCharacter.getFaction();
				if (o.toString().equals(s.toString())) {
					AppPanelCharacter.dropCharFaction.setSelectedIndex(i);
				}
			}
		}

		catch (java.lang.NullPointerException e) {

		}

		// load image:

		try {
			if (selectedCharacter.getImage().length() > 0) {
				ImageIcon icon = new ImageIcon(selectedCharacter.getImage());
				Image img = icon.getImage();
				Image tmpImg = img.getScaledInstance(AppDetailsNote.imagePanel
						.getWidth(), -1, Image.SCALE_FAST);
				ImageIcon newIcon = new ImageIcon(tmpImg);
				JLabel image = new JLabel();
				image.setIcon(newIcon);
				AppDetailsNote.imagePanel.removeAll();
				AppDetailsNote.imagePanel.repaint();
				AppDetailsNote.imagePanel.add(image);
				AppDetailsNote.imagePanel.setVisible(true);
			}
		} catch (NullPointerException e) {

		}

	}

	public void showCharacterOverview() {
		disableMenuItems();
		showDetails();
		StoryLineAppGUI.mnCharacter.setVisible(true);
		StoryLineAppGUI.panelContent.removeAll();
		charsList.removeAllElements();
		StoryLineAppGUI.panelContent.repaint();
		StoryLineAppGUI.panelContent.add(panelCharacterOverview);
		charsList = new DefaultListModel();
		String s = path.getLastPathComponent().toString();
		listChars = new JList(charsList);
		listChars.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listChars.addListSelectionListener(this);
		AppPanelCharacterOverview.scrollCharOverview.setViewportView(listChars);
		ArrayList<Character> characters = activeCharacters;
		int a = characters.size();
		if (s.toString().equals("Main Cast")) {
			for (int i = 0; i < a; i++) {
				Character tmp = characters.get(i);
				if (tmp.getRole().toString().equals(s)) {
					charsList.addElement(characters.get(i));
				}
			}
		}
		if (s.toString().equals("Support Cast")) {
			for (int i = 0; i < a; i++) {
				Character tmp = characters.get(i);
				if (tmp.getRole().toString().equals(s)) {
					charsList.addElement(characters.get(i));
				}
			}
		}
		if (s.toString().equals("Extras")) {
			for (int i = 0; i < a; i++) {
				Character tmp = characters.get(i);
				if (tmp.getRole().toString().equals(s)) {
					charsList.addElement(characters.get(i));
				}
			}
		}
		if (s.toString().equals("Characters")) {
			for (int i = 0; i < a; i++) {
				charsList.addElement(characters.get(i));
			}
		}
	}

	public void whatLocation() {
		String s = path.getLastPathComponent().toString();
		if (s != null) {
			ArrayList<Location> locations = activeLocations;
			for (int i = 0; i < locations.size(); i++) {
				Location tmp = locations.get(i);
				if (tmp.toString().equals(s)) {
					selectedLocation = tmp;
				}
			}
		}
	}

	public void showLocation(Location l) {
		selectedLocation = l;
		whatLocation();
		showDetails();
		disableMenuItems();
		AppPanelLocation.btnChapterEdit.setText("Save");
		StoryLineAppGUI.mnLocation.setVisible(true);
		StoryLineAppGUI.panelContent.removeAll();
		StoryLineAppGUI.panelContent.repaint();
		StoryLineAppGUI.panelContent.add(panelLocation);
		AppPanelLocation.txtLocCity.setText(selectedLocation.getCity());
		AppPanelLocation.txtLocCountry.setText(selectedLocation.getCountry());
		AppPanelLocation.txtLocImage.setText(selectedLocation.getImage());
		AppPanelLocation.txtLocMap.setText(selectedLocation.getMap());
		AppPanelLocation.txtLocName.setText(selectedLocation.getName());
		AppPanelLocation.txtLocShortName.setText(selectedLocation
				.getShortName());
		AppPanelLocation.txtLocWeb.setText(selectedLocation.getWeb());
		AppPanelLocation.taLocAddress.setText(selectedLocation.getAddress());
		AppPanelLocation.taLocDesc.setText(selectedLocation.getDescription());
		AppPanelLocation.btnLocWeb.setText("Add Weblink");
		AppPanelLocation.btnLocImage.setText("Add Image");
		try {
			if (selectedLocation.getWeb().equals("") == false) {
				AppPanelLocation.btnLocWeb.setText("View Weblink");
			}
		} catch (NullPointerException e) {
		}
		;
		try {
			if (selectedLocation.getImage().equals("") == false) {
				AppPanelLocation.btnLocImage.setText("Change Image");
			}
		} catch (NullPointerException e) {
		}
		try {
			if (selectedLocation.getImage().length() > 0) {
				ImageIcon icon = new ImageIcon(selectedLocation.getImage());
				Image img = icon.getImage();
				Image tmpImg = img.getScaledInstance(AppDetailsNote.imagePanel
						.getWidth(), -1, Image.SCALE_FAST);
				ImageIcon newIcon = new ImageIcon(tmpImg);
				JLabel image = new JLabel();
				image.setIcon(newIcon);
				AppDetailsNote.imagePanel.removeAll();
				AppDetailsNote.imagePanel.repaint();
				AppDetailsNote.imagePanel.add(image);
				AppDetailsNote.imagePanel.setVisible(true);
			}
		} catch (NullPointerException e) {

		}
	}

	public void showLocationOverview() {
		disableMenuItems();
		showDetails();
		StoryLineAppGUI.mnLocation.setVisible(true);
		StoryLineAppGUI.panelContent.removeAll();
		StoryLineAppGUI.panelContent.repaint();
		StoryLineAppGUI.panelContent.add(panelLocacionOverview);
		locationList = new DefaultListModel();
		listLocations = new JList(locationList);
		listLocations.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listLocations.addListSelectionListener(this);
		AppPanelLocationOverview.scrollLocOverview
				.setViewportView(listLocations);
		ArrayList<Location> locations = activeLocations;
		for (int i = 0; i < locations.size(); i++) {
			locationList.addElement(locations.get(i));
		}
	}

	public void whatFaction() {
		String s = path.getLastPathComponent().toString();
		if (s != null) {
			ArrayList<Faction> factions = activeFactions;
			for (int i = 0; i < factions.size(); i++) {
				Faction tmp = factions.get(i);
				if (tmp.toString().equals(s)) {
					selectedFaction = tmp;
				}
			}
		}
	}

	public void showFaction(Faction c) {
		selectedFaction = c;
		whatFaction();
		showDetails();
		disableMenuItems();
		AppPanelFaction.btnChapterEdit.setText("Save");
		StoryLineAppGUI.mnFaction.setVisible(true);
		StoryLineAppGUI.panelContent.removeAll();
		AppPanelFaction.dropFactionAffilation.removeAllItems();
		AppPanelFaction.dropFactionRole.removeAllItems();
		StoryLineAppGUI.panelContent.repaint();
		StoryLineAppGUI.panelContent.add(panelFaction);
		AppPanelFaction.txtFactionName.setText(selectedFaction.getName());
		AppPanelFaction.txtFactionShortName.setText(selectedFaction
				.getShortName());
		AppPanelFaction.taFactionDesc.setText(selectedFaction.getDescription());
		for (int i = 0; i < Roles.length; i++) {
			AppPanelFaction.dropFactionRole.addItem(Roles[i]);
		}
		for (int i = 0; i < AppPanelFaction.dropFactionRole.getItemCount(); i++) {
			Object o = AppPanelFaction.dropFactionRole.getItemAt(i);
			String s = selectedFaction.getRole();
			if (o.toString().equals(s)) {
				AppPanelFaction.dropFactionRole.setSelectedIndex(i);
			}
		}
		for (int i = 0; i < Affilation.length; i++) {
			AppPanelFaction.dropFactionAffilation.addItem(Affilation[i]);
		}
		for (int i = 0; i < AppPanelFaction.dropFactionAffilation
				.getItemCount(); i++) {
			Object o = AppPanelFaction.dropFactionAffilation.getItemAt(i);
			String s = selectedFaction.getAffilation();
			if (o.toString().equals(s)) {
				AppPanelFaction.dropFactionAffilation.setSelectedIndex(i);
			}
		}

	}

	public void showFactionOverview() {
		disableMenuItems();
		showDetails();
		StoryLineAppGUI.mnFaction.setVisible(true);
		StoryLineAppGUI.panelContent.removeAll();
		StoryLineAppGUI.panelContent.repaint();
		StoryLineAppGUI.panelContent.add(panelFactionOverview);
		factionList = new DefaultListModel();
		listFactions = new JList(factionList);
		listFactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listFactions.addListSelectionListener(this);
		AppPanelFactionOverview.scrollFactionOverview
				.setViewportView(listFactions);
		ArrayList<Faction> factions = activeFactions;
		for (int i = 0; i < factions.size(); i++) {
			factionList.addElement(factions.get(i));
		}

	}

	public void whatPlot() {
		String s = path.getLastPathComponent().toString();
		if (s != null) {
			ArrayList<Plot> plots = activePlots;
			for (int i = 0; i < plots.size(); i++) {
				Plot tmp = plots.get(i);
				if (tmp.toString().equals(s)) {
					selectedPlot = tmp;
				}
			}
		}
	}

	public void showPlot(Plot c) {
		selectedPlot = c;
		whatPlot();
		showDetails();
		disableMenuItems();
		StoryLineAppGUI.mnPlot.setVisible(true);
		StoryLineAppGUI.panelContent.removeAll();
		AppPanelPlot.dropPlotFaction.removeAllItems();
		StoryLineAppGUI.panelContent.repaint();
		StoryLineAppGUI.panelContent.add(panelPlot);
		AppPanelPlot.txtPlotName.setText(selectedPlot.getName());
		AppPanelPlot.taPlotDesc.setText(selectedPlot.getDescription());
		DefaultListModel plotSceneList = new DefaultListModel();
		locationList = new DefaultListModel();
		JList listPlotScenes = new JList(plotSceneList);
		listLocations = new JList(locationList);
		listPlotScenes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listPlotScenes.addListSelectionListener(this);
		listLocations.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listLocations.addListSelectionListener(this);
		AppPanelPlot.scrollPlotScenes.setViewportView(listPlotScenes);
		ArrayList<String> scenes = selectedPlot.getScenes();
		ArrayList<Faction> factions = activeFactions;

		for (int i = 0; i < scenes.size(); i++) {
			plotSceneList.addElement(scenes.get(i));
		}
		for (int i = 0; i < factions.size(); i++) {
			AppPanelPlot.dropPlotFaction.addItem(factions.get(i));
		}
		for (int i = 0; i < AppPanelPlot.dropPlotFaction.getItemCount(); i++) {
			Object o = AppPanelPlot.dropPlotFaction.getItemAt(i);
			String s = selectedPlot.getFaction();
			if (o.toString().equals(s)) {
				AppPanelPlot.dropPlotFaction.setSelectedIndex(i);
			}
		}
	}

	public void showPlotOverview() {
		disableMenuItems();
		showDetails();
		StoryLineAppGUI.mnPlot.setVisible(true);
		StoryLineAppGUI.panelContent.removeAll();
		StoryLineAppGUI.panelContent.repaint();
		StoryLineAppGUI.panelContent.add(panelPlotOverview);
		plotList = new DefaultListModel();
		listPlots = new JList(plotList);
		listPlots.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listPlots.addListSelectionListener(this);
		AppPanelPlotOverview.scrollPlotOverview.setViewportView(listPlots);
		ArrayList<Plot> plots = activePlots;
		for (int i = 0; i < plots.size(); i++) {
			plotList.addElement(plots.get(i));
		}
	}

	public void whatNote() {
		String s = path.getLastPathComponent().toString();
		if (s != null) {
			ArrayList<Note> notes = activeNotes;
			for (int i = 0; i < notes.size(); i++) {
				Note tmp = notes.get(i);
				if (tmp.toString().equals(s)) {
					selectedNote = tmp;
				}
			}
		}
	}

	// these functions are responsilbe for the jtree

	public void buildTree() {
		// this builds the JTree
		treeStory = new DefaultMutableTreeNode(activeStory.toString());// this
																		// is
																		// the
																		// model
																		// for
																		// our
																		// tree
		createNodes();// now create the nodes for our tree
		storytree = new JTree(treeStory);// this is the actual displayed tree
		storytree.getSelectionModel().setSelectionMode(
				TreeSelectionModel.SINGLE_TREE_SELECTION);
		storytree.getSelectionModel().addTreeSelectionListener(this);// add a
																		// listner
																		// to
																		// our
																		// tree
		StoryLineAppGUI.scrollTree.setViewportView(storytree);// lets display
																// our tree
		if (isExpanded == false)
			expandAll(storytree);// now expand all nodes by default
	}

	public void createNodes() {

		DefaultMutableTreeNode rootChapters = new DefaultMutableTreeNode(
				"Chapters");
		treeStory.add(rootChapters);

		// add a subnode for each chapter
		// get all the chapters of the story
		// get the # of chapters
		int x = activeChapters.size();
		// for each chapter in the list
		for (int i = 0; i < x; i++) {

			Chapter tmpChapter = activeChapters.get(i);
			// add a node
			DefaultMutableTreeNode nodeChapter = new DefaultMutableTreeNode(
					tmpChapter.toString());
			rootChapters.add(nodeChapter);

			// add a node for scenes
			DefaultMutableTreeNode nodeScenes = new DefaultMutableTreeNode(
					"Scenes");
			nodeChapter.add(nodeScenes);

			/*
			 * //add a node for notes DefaultMutableTreeNode nodeNotes = new
			 * DefaultMutableTreeNode("Notes"); nodeChapter.add(nodeNotes);
			 */

			// add a subnode for each scene in this chapter
			ArrayList<Scene> alChapterScenes = tmpChapter.getScenes();
			Collections.sort(alChapterScenes);
			int z = alChapterScenes.size();
			for (int k = 0; k < z; k++) {
				Scene tmpScene = alChapterScenes.get(k);
				DefaultMutableTreeNode leafScene = new DefaultMutableTreeNode(
						tmpScene.toString());
				nodeScenes.add(leafScene);
			}

			/*
			 * //add a subnode for each note in this chapter ArrayList<Note>
			 * alChapterNotes = tmpChapter.getNotes(); int y =
			 * alChapterNotes.size(); for (int j = 0; j < y; j++){ Note tmpNote
			 * = alChapterNotes.get(j); DefaultMutableTreeNode leafNotes = new
			 * DefaultMutableTreeNode(tmpNote.toString());
			 * nodeNotes.add(leafNotes); }
			 */
		}

		DefaultMutableTreeNode rootCharacters = new DefaultMutableTreeNode(
				"Characters");
		treeStory.add(rootCharacters);

		DefaultMutableTreeNode nodeMainCast = new DefaultMutableTreeNode(
				"Main Cast");
		rootCharacters.add(nodeMainCast);

		int zz = activeCharacters.size();
		for (int a = 0; a < zz; a++) {
			Character tmp = activeCharacters.get(a);
			String Role = tmp.getRole();
			if (Role.equals("Main Cast") == true) {
				DefaultMutableTreeNode leafMainCast = new DefaultMutableTreeNode(
						tmp.toString());
				nodeMainCast.add(leafMainCast);
			}
		}

		DefaultMutableTreeNode nodeSupportCast = new DefaultMutableTreeNode(
				"Support Cast");
		rootCharacters.add(nodeSupportCast);

		int zzz = activeCharacters.size();
		for (int a = 0; a < zzz; a++) {
			Character tmp = activeCharacters.get(a);
			String Role = tmp.getRole();
			if (Role.equals("Support Cast") == true) {
				DefaultMutableTreeNode leafSupportCast = new DefaultMutableTreeNode(
						tmp.toString());
				nodeSupportCast.add(leafSupportCast);
			}
		}

		DefaultMutableTreeNode nodeExtras = new DefaultMutableTreeNode("Extras");
		rootCharacters.add(nodeExtras);

		int zzzz = activeCharacters.size();
		for (int a = 0; a < zzzz; a++) {
			Character tmp = activeCharacters.get(a);
			String Role = tmp.getRole();
			if (Role.equals("Extras") == true) {
				DefaultMutableTreeNode leafExtras = new DefaultMutableTreeNode(
						tmp.toString());
				nodeExtras.add(leafExtras);
			}
		}

		DefaultMutableTreeNode rootLocations = new DefaultMutableTreeNode(
				"Locations");
		treeStory.add(rootLocations);

		int y = activeLocations.size();
		for (int a = 0; a < y; a++) {
			Location tmp = activeLocations.get(a);
			DefaultMutableTreeNode leafLocation = new DefaultMutableTreeNode(
					tmp.toString());
			rootLocations.add(leafLocation);
		}

		DefaultMutableTreeNode rootFactions = new DefaultMutableTreeNode(
				"Factions");
		treeStory.add(rootFactions);

		int yy = activeFactions.size();
		for (int a = 0; a < yy; a++) {
			Faction tmp = activeFactions.get(a);
			DefaultMutableTreeNode nodeFaction = new DefaultMutableTreeNode(tmp);
			rootFactions.add(nodeFaction);
		}

		DefaultMutableTreeNode rootPlots = new DefaultMutableTreeNode("Plots");
		treeStory.add(rootPlots);

		int yyy = activePlots.size();
		for (int a = 0; a < yyy; a++) {
			Plot tmp = activePlots.get(a);
			DefaultMutableTreeNode nodePlot = new DefaultMutableTreeNode(tmp);
			rootPlots.add(nodePlot);
		}
	}

	// function exandAll
	// this expands the tree
	public void expandAll(JTree storyTree) {
		/*
		 * int row = 0; while (row < storyTree.getRowCount()) {
		 * storyTree.expandRow(row); row++; } isExpanded = true;
		 */
	}

	public void loadActiveStory() {

		ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded
				.newConfiguration(), dbFile);

		try {
			db.query(Story.class);

			Query query = db.query();
			query.constrain(Story.class);
			ObjectSet<?> result = query.execute();
			activeStory = (Story) result.get(0);
			StoryAuthor = activeStory.getStoryAuthor();
			System.out.println("active story: " + activeStory.toString());
			System.out.println("author: "+StoryAuthor.toString());

		}

		finally {
			db.close();
		}
	}

	public void loadChapters() {

		ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded
				.newConfiguration(), dbFile);

		try {
			ObjectSet<Chapter> result = db.queryByExample(Chapter.class);
			while (result.hasNext()) {
				Chapter tmp = (Chapter) result.next();
				activeChapters.add(tmp);
			}
			Collections.sort(activeChapters);

		}

		finally {
			db.close();
		}
	}

	public void loadCharacters() {
		ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded
				.newConfiguration(), dbFile);

		try {
			ObjectSet<Character> result = db.queryByExample(Character.class);
			while (result.hasNext()) {
				Character tmp = (Character) result.next();
				activeCharacters.add(tmp);
			}

		}

		finally {
			db.close();
		}

	}

	public void loadFactions() {

		ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded
				.newConfiguration(), dbFile);

		try {
			ObjectSet<Faction> result = db.queryByExample(Faction.class);
			while (result.hasNext()) {
				Faction tmp = (Faction) result.next();
				activeFactions.add(tmp);
			}

		}

		finally {
			db.close();
		}
	}

	public void loadLocs() {

		ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded
				.newConfiguration(), dbFile);

		try {
			ObjectSet<Location> result = db.queryByExample(Location.class);
			while (result.hasNext()) {
				Location tmp = (Location) result.next();
				activeLocations.add(tmp);
			}

		}

		finally {
			db.close();
		}
	}

	public void loadPlots() {

		ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded
				.newConfiguration(), dbFile);

		try {
			ObjectSet<Plot> result = db.queryByExample(Plot.class);
			while (result.hasNext()) {
				Plot tmp = (Plot) result.next();
				activePlots.add(tmp);
			}

		}

		finally {
			db.close();
		}
	}

	public void loadNotes() {

		ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded
				.newConfiguration(), dbFile);

		try {
			ObjectSet<Note> result = db.queryByExample(Note.class);
			while (result.hasNext()) {
				Note tmp = (Note) result.next();
				activeNotes.add(tmp);
			}

		}

		finally {
			db.close();
		}
	}


	private void disableChapterButtons() {
		AppPanelChapterOverview.btnNrDown.setVisible(false);
		AppPanelChapterOverview.btnNrUp.setVisible(false);
		AppPanelChapterOverview.lblChapterNr.setVisible(false);

	}

	private void selectCharImage() {
		// TODO Crate a dialog to selectet a image file
		final JFileChooser chooser = new JFileChooser("Please select an image");
		chooser.setDialogType(JFileChooser.OPEN_DIALOG);
		chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		final File file = new File("/home");

		chooser.setCurrentDirectory(file);

		chooser.addPropertyChangeListener(new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent e) {
				if (e.getPropertyName().equals(
						JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
						|| e.getPropertyName().equals(
								JFileChooser.DIRECTORY_CHANGED_PROPERTY)) {
					e.getNewValue();
				}
			}
		});

		chooser.setVisible(true);
		final int result = chooser.showOpenDialog(null);

		if (result == JFileChooser.APPROVE_OPTION) {
			File inputVerzFile = chooser.getSelectedFile();
			String inputVerzStr = inputVerzFile.getPath();
			System.out.println(inputVerzStr);

			getFileType(inputVerzStr);
			String c = selectedCharacter.getName()
					+ selectedCharacter.getNickName()
					+ selectedCharacter.getFirstName();
			String t = homePath + "/StoryLine/" + story + "/images/" + c + "."
					+ getFileType(inputVerzStr);
			File target = new File(t);
			try {
				copyFile(inputVerzFile, target);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			AppPanelCharacter.txtImageUrl.setText(target.toString());

		}
		System.out.println("done");
		chooser.setVisible(false);

		editCharacter();

	}

	private void selectLocImage() {
		// TODO Crate a dialog to selectet a image file
		final JFileChooser chooser = new JFileChooser("Please select an image");
		chooser.setDialogType(JFileChooser.OPEN_DIALOG);
		chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		final File file = new File("/home");

		chooser.setCurrentDirectory(file);

		chooser.addPropertyChangeListener(new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent e) {
				if (e.getPropertyName().equals(
						JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
						|| e.getPropertyName().equals(
								JFileChooser.DIRECTORY_CHANGED_PROPERTY)) {
				}
			}
		});

		chooser.setVisible(true);
		final int result = chooser.showOpenDialog(null);

		if (result == JFileChooser.APPROVE_OPTION) {
			File inputVerzFile = chooser.getSelectedFile();
			String inputVerzStr = inputVerzFile.getPath();
			System.out.println(inputVerzStr);

			getFileType(inputVerzStr);
			String c = selectedLocation.toString();
			String t = homePath + "/StoryLine/" + story + "/images/" + c + "."
					+ getFileType(inputVerzStr);
			File target = new File(t);
			try {
				copyFile(inputVerzFile, target);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			AppPanelLocation.txtLocImage.setText(target.toString());

		}
		System.out.println("done");
		chooser.setVisible(false);

		editLocation();

	}

	private String getFileType(String s) {
		String fileType;
		int x = s.length();
		fileType = s.substring(x - 3);
		return fileType;

	}

	public static void copyFile(File in, File out) throws IOException {
		FileChannel inChannel = new FileInputStream(in).getChannel();
		FileChannel outChannel = new FileOutputStream(out).getChannel();
		try {
			inChannel.transferTo(0, inChannel.size(), outChannel);
		} catch (IOException e) {
			throw e;
		} finally {
			if (inChannel != null)
				inChannel.close();
			if (outChannel != null)
				outChannel.close();
		}
	}

	private void createLocationOverview() {
		String input = JOptionPane.showInputDialog(null,
				"Enter a name for your location:", "Create a new loaction",
				JOptionPane.PLAIN_MESSAGE);
		if (input == null) {
			return;
		}
		if (input.equals("") == false) {
			Location tmp = new Location();
			tmp.setName(input);
			tmp.setShortName("L" + activeLocations.size());
			tmp.dbCreateLocation(dbFile);
			activeLocations.add(tmp);
			selectedLocation = tmp;
			updateTree();
			showLocationOverview();
		}

	}

	private void deleteLocationOverview() {
		try {
			int n = JOptionPane.showConfirmDialog(panelLocacionOverview,
					"Do you really want to delete this?", "Warning",
					JOptionPane.OK_CANCEL_OPTION);
			if (n == JOptionPane.YES_OPTION) {
				selectedLocation = (Location) listLocations.getSelectedValue();
				selectedLocation.dbDeleteLocationr(dbFile);
				activeLocations.remove(selectedLocation);
				updateTree();
				showLocationOverview();
			}
		} catch (NullPointerException e) {
			StoryLineAppGUI.lblStatusOutput.setText("nothing selected");
		}

	}

	private void editLocationOverview() {
		selectedLocation = (Location) listLocations.getSelectedValue();
		updateTree();
		showLocation(selectedLocation);

	}

	private void createLocationPanel() {
		Location tmp = new Location();
		tmp.setAddress(AppPanelLocation.taLocAddress.getText());
		tmp.setCity(AppPanelLocation.txtLocCity.getText());
		tmp.setCountry(AppPanelLocation.txtLocCountry.getText());
		tmp.setDescription(AppPanelLocation.taLocDesc.getText());
		tmp.setImage(AppPanelLocation.txtLocImage.getText());
		tmp.setMap(AppPanelLocation.txtLocMap.getText());
		tmp.setName(AppPanelLocation.txtLocName.getText());
		tmp.setShortName(AppPanelLocation.txtLocShortName.getText());
		tmp.setWeb(AppPanelLocation.txtLocWeb.getText());
		tmp.dbCreateLocation(dbFile);
		activeLocations.add(tmp);
		selectedLocation = tmp;
		updateTree();
		showLocation(tmp);

	}

	private void deleteLocationPanel() {

		try {
			int n = JOptionPane.showConfirmDialog(panelLocacionOverview,
					"Do you really want to delete this?", "Warning",
					JOptionPane.OK_CANCEL_OPTION);
			if (n == JOptionPane.YES_OPTION) {
				whatLocation();
				Location tmp = selectedLocation;
				tmp.dbDeleteLocationr(dbFile);
				activeLocations.remove(tmp);
				updateTree();
				showLocationOverview();
			}
		} catch (NullPointerException e) {
			StoryLineAppGUI.lblStatusOutput.setText("nothing selected");
		}

	}

	private void editLocation() {
		Location tmp = new Location();
		tmp.setAddress(AppPanelLocation.taLocAddress.getText());
		tmp.setCity(AppPanelLocation.txtLocCity.getText());
		tmp.setCountry(AppPanelLocation.txtLocCountry.getText());
		tmp.setDescription(AppPanelLocation.taLocDesc.getText());
		tmp.setImage(AppPanelLocation.txtLocImage.getText());
		tmp.setMap(AppPanelLocation.txtLocMap.getText());
		tmp.setName(AppPanelLocation.txtLocName.getText());
		tmp.setShortName(AppPanelLocation.txtLocShortName.getText());
		tmp.setWeb(AppPanelLocation.txtLocWeb.getText());
		selectedLocation.dbEditLocation(dbFile, tmp);
		updateTree();
		showLocation(tmp);

	}

	private void createFactionOverview() {
		String input = JOptionPane.showInputDialog(null,
				"Enter a name for your faction:", "Create a new faction",
				JOptionPane.PLAIN_MESSAGE);
		if (input == null) {
			return;
		}
		if (input.equals("") == false) {
			Faction tmp = new Faction();
			tmp.setName(input);
			tmp.setShortName("F" + activeFactions.size());
			tmp.dbCreateFaction(dbFile);
			activeFactions.add(tmp);
			updateTree();
			showFactionOverview();
		}

	}

	private void deleteFactionOverview() {
		try {
			int n = JOptionPane.showConfirmDialog(panelLocacionOverview,
					"Do you really want to delete this?", "Warning",
					JOptionPane.OK_CANCEL_OPTION);
			if (n == JOptionPane.YES_OPTION) {
				selectedFaction = (Faction) listFactions.getSelectedValue();
				selectedFaction.dbDeleteFaction(dbFile);
				activeFactions.remove(selectedFaction);
				updateTree();
				showFactionOverview();
			}
		} catch (NullPointerException e) {
			StoryLineAppGUI.lblStatusOutput.setText("nothing selected");
		}

	}

	private void editFactionOverview() {
		selectedFaction = (Faction) listFactions.getSelectedValue();
		updateTree();
		showFaction(selectedFaction);
	}

	private void createFactionPanel() {
		Faction tmp = new Faction();
		tmp.setAffilation(AppPanelFaction.dropFactionAffilation
				.getSelectedItem().toString());
		tmp.setDescription(AppPanelFaction.taFactionDesc.getText());
		tmp.setName(AppPanelFaction.txtFactionName.getText());
		tmp.setRole(AppPanelFaction.dropFactionRole.getSelectedItem()
				.toString());
		tmp.setShortName(AppPanelFaction.txtFactionShortName.getText());
		tmp.dbCreateFaction(dbFile);
		activeFactions.add(tmp);
		updateTree();
		showFaction(tmp);

	}

	private void deleteFactionPanel() {

		int n = JOptionPane.showConfirmDialog(panelLocacionOverview,
				"Do you really want to delete this?", "Warning",
				JOptionPane.OK_CANCEL_OPTION);
		if (n == JOptionPane.YES_OPTION) {
			whatFaction();
			selectedFaction.dbDeleteFaction(dbFile);
			activeFactions.remove(selectedFaction);
			updateTree();
			showFactionOverview();
		}

	}

	private void editFaction() {
		Faction tmp = new Faction();
		tmp.setCharacters(selectedFaction.getCharacters());
		tmp.setAffilation(AppPanelFaction.dropFactionAffilation
				.getSelectedItem().toString());
		tmp.setDescription(AppPanelFaction.taFactionDesc.getText());
		tmp.setName(AppPanelFaction.txtFactionName.getText());
		tmp.setRole(AppPanelFaction.dropFactionRole.getSelectedItem()
				.toString());
		tmp.setShortName(AppPanelFaction.txtFactionShortName.getText());
		;
		selectedFaction.dbEditFaction(dbFile, tmp);
		updateTree();
		showFaction(selectedFaction);

	}

	private void createPlotOverview() {
		String input = JOptionPane.showInputDialog(null,
				"Enter a name for your plot:", "Create a new plot",
				JOptionPane.PLAIN_MESSAGE);
		if (input == null) {
			return;
		}
		if (input.equals("") == false) {
			Plot tmp = new Plot();
			tmp.setName(input);
			tmp.dbCreatePlot(dbFile);
			activePlots.add(tmp);
			updateTree();
			showPlotOverview();
		}

	}

	private void deletePlotOverview() {
		try {
			int n = JOptionPane.showConfirmDialog(panelLocacionOverview,
					"Do you really want to delete this?", "Warning",
					JOptionPane.OK_CANCEL_OPTION);
			if (n == JOptionPane.YES_OPTION) {
				selectedPlot = (Plot) listPlots.getSelectedValue();
				selectedPlot.dbDeletePlot(dbFile);
				activePlots.remove(selectedPlot);
				updateTree();
				showPlotOverview();
			}
		} catch (NullPointerException e) {
			StoryLineAppGUI.lblStatusOutput.setText("nothing selected");
		}

	}

	private void editPlotOverview() {
		selectedPlot = (Plot) listPlots.getSelectedValue();
		updateTree();
		showPlot(selectedPlot);

	}

	private void createPlotPanel() {
		Plot tmp = new Plot();
		tmp.setDescription(AppPanelPlot.taPlotDesc.getText());
		tmp.setFaction(AppPanelPlot.dropPlotFaction.getSelectedItem()
				.toString());
		tmp.setName(AppPanelPlot.txtPlotName.getText());
		tmp.dbCreatePlot(dbFile);
		activePlots.add(tmp);
		updateTree();
		showPlot(tmp);

	}

	private void deletePlotPanel() {

		int n = JOptionPane.showConfirmDialog(panelLocacionOverview,
				"Do you really want to delete this?", "Warning",
				JOptionPane.OK_CANCEL_OPTION);
		if (n == JOptionPane.YES_OPTION) {
			whatPlot();
			selectedPlot.dbDeletePlot(dbFile);
			activePlots.remove(selectedPlot);
			updateTree();
			showPlotOverview();
		}

	}

	private void editPlot() {
		Plot tmp = new Plot();
		tmp.setDescription(AppPanelPlot.taPlotDesc.getText());
		tmp.setFaction(AppPanelPlot.dropPlotFaction.getSelectedItem()
				.toString());
		tmp.setName(AppPanelPlot.txtPlotName.getText());
		tmp.setScenes(selectedPlot.getScenes());
		selectedPlot.dbEditPlot(dbFile, tmp);
		updateTree();
		showPlot(tmp);

	}

	public void updateTree() {
		// TODO: get last element
		activeChapters.trimToSize();
		activeCharacters.trimToSize();
		activeFactions.trimToSize();
		activeLocations.trimToSize();
		activeNotes.trimToSize();
		activePlots.trimToSize();
		buildTree();
		// TODO: expand last element
	}

	public void createChapterOverview() {
		String input = JOptionPane.showInputDialog(null,
				"Enter a name for your Chapter:", "Create a new chapter",
				JOptionPane.PLAIN_MESSAGE);
		if (input == null) {
			return;
		}
		if (input.equals("") == false) {
			Chapter tmp = new Chapter();
			tmp.setName(input);
			tmp.dbCreateChapter(dbFile);
			StoryLineAppGUI.lblStatusOutput.setText("Chapter: '"
					+ tmp.getName() + "' created.");
			activeChapters.add(tmp);
			updateTree();
		}

	}

	public void createChapterPanel() {
		Chapter tmp = new Chapter();
		tmp.setName(AppPanelChapter.txtChapterName.getText());
		tmp.setDescription(AppPanelChapter.editorChapterDesc.getText());
		tmp.dbCreateChapter(dbFile);
		activeChapters.add(tmp);
		updateTree();
	}

	public void deleteChapter() {

		int n = JOptionPane.showConfirmDialog(panelLocacionOverview,
				"Do you really want to delete this?", "Warning",
				JOptionPane.OK_CANCEL_OPTION);
		if (n == JOptionPane.YES_OPTION) {
			System.out.println(selectedChapter);
			selectedChapter.dbDeleteChapter(dbFile);
			activeChapters.remove(selectedChapter);
			updateTree();
			showChapterOverview();
		}
	}

	public void deleteChapterOverview() {
		try {
			int n = JOptionPane.showConfirmDialog(panelLocacionOverview,
					"Do you really want to delete this?", "Warning",
					JOptionPane.OK_CANCEL_OPTION);
			if (n == JOptionPane.YES_OPTION) {
				Chapter del = (Chapter) listChapters.getSelectedValue();
				for (int i = 0; i < activeChapters.size(); i++)
					if (del.toString().equals(activeChapters.get(i).toString())) {
						activeChapters.get(i).dbDeleteChapter(dbFile);
						activeChapters.remove(i);
					}
				updateTree();
				showChapterOverview();
			}
		} catch (NullPointerException e) {
			StoryLineAppGUI.lblStatusOutput.setText("nothing selected");
		}
	}

	public void editChapterOverview() {
		selectedChapter = (Chapter) listChapters.getSelectedValue();
		updateTree();
		showChapter(selectedChapter);
	}

	public void editChapter() {
		Chapter tmp = new Chapter();
		ArrayList<Note> notes = new ArrayList<Note>();
		for (int i = 0; i < chapterNoteList.size(); i++) {
			Note n = (Note) chapterNoteList.get(i);
			notes.add(n);
		}
		tmp.setScenes(selectedChapter.getScenes());
		tmp.setDescription(AppPanelChapter.editorChapterDesc.getText());
		tmp.setName(AppPanelChapter.txtChapterName.getText());
		tmp.setNr(selectedChapter.getNr());

		for (int i = 0; i < activeChapters.size(); i++) {
			Chapter ch = activeChapters.get(i);
			if (ch.equals(selectedChapter)) {
				System.out.println("found");

				selectedChapter.dbEditChapter(dbFile, tmp);
				activeChapters.set(i, tmp);
			}
		}
		updateTree();
	}

	public void chapterNrDown() {
		// TODO: save changes to db
		activeStory.chapterNrDown(activeChapters, selectedChapter);
		Chapter update = selectedChapter;
		update.dbEditChapter(dbFile, selectedChapter);
		Collections.sort(activeChapters);
		buildTree();
		expandChapters();
	}

	public void chapterNrUp() {
		// TODO: save changes to db
		activeStory.chapterNrUp(activeChapters, selectedChapter);
		Chapter update = selectedChapter;
		update.dbEditChapter(dbFile, selectedChapter);
		Collections.sort(activeChapters);
		buildTree();
		expandChapters();
	}

	public void sceneNrDown() {
		selectedChapter.dbSceneNrDown(dbFile, selectedScene);
		selectedChapter.dbSceneUpdate(dbFile, selectedChapter.scenes
				.indexOf(selectedScene), selectedScene);
		buildTree();
		expandChapters();
		expandScenes();
	}

	public void sceneNrUp() {
		selectedChapter.dbSceneNrUp(dbFile, selectedScene);
		selectedChapter.dbSceneUpdate(dbFile, selectedChapter.scenes
				.indexOf(selectedScene), selectedScene);
		buildTree();
		expandChapters();
		expandScenes();
	}

	public void createSceneOverview() {
		String input = JOptionPane.showInputDialog(null,
				"Enter a name for your scene:", "Create a new scene",
				JOptionPane.PLAIN_MESSAGE);
		if (input == null) {
			return;
		}
		if (input.equals("") == false) {
			Scene tmp = new Scene();
			tmp.setName(input);
			createScene(tmp);
		}
	}

	public void createScenePanel() {
		Scene tmp = new Scene();
		createScene(tmp);
		showScenesOverview();

	}

	public void createScene(Scene tmp) {
		whatScene();
		if (tmp.getNr() < 0) {
			tmp.setNr(selectedChapter.scenes.size() + 1);
		}
		selectedChapter.dbSceneCreateScene(dbFile, tmp);
		activeChapters.set(selectedChapter.getNr() - 1, selectedChapter);
		StoryLineAppGUI.lblStatusOutput.setText("Scene: " + tmp.toString()
				+ " added");
		updateTree();
	}

	public void deleteSceneOverview() {

		try {
			selectedScene = (Scene) listScenes.getSelectedValue();
			deleteScene();
		} catch (NullPointerException e) {
			StoryLineAppGUI.lblStatusOutput.setText("nothing selected");
		}

	}

	public void deleteScene() {

		int n = JOptionPane.showConfirmDialog(panelLocacionOverview,
				"Do you really want to delete this?", "Warning",
				JOptionPane.OK_CANCEL_OPTION);
		if (n == JOptionPane.YES_OPTION) {
			whatScene();
			ArrayList<Scene> scenes = selectedChapter.getScenes();
			scenes.remove(selectedScene);
			// TODO: remove scene from plots
			Plot tmpP = new Plot();
			ArrayList<String> tmpScenes = new ArrayList<String>();
			int indexP = -1;
			for (int i = 0; i < activePlots.size(); i++) {
				Plot p = activePlots.get(i);
				ArrayList<String> pscenes = p.getScenes();
				for (int j = 0; j < pscenes.size(); j++) {
					String pS = pscenes.get(j);
					if (pS.toString().equals(selectedScene.toString())) {
						pscenes.remove(j);
						p.dbSceneDelete(dbFile, selectedScene.toString());
						tmpScenes = pscenes;
						indexP = i;
						tmpP = p;
					}
				}
			}
			tmpP.setScenes(tmpScenes);
			activePlots.set(indexP + 1, tmpP);
			selectedChapter.dbSceneRemove(dbFile, selectedScene);
			updateTree();
			showScenesOverview();
		}
	}

	public void editSceneOverview() {
		selectedScene = (Scene) listScenes.getSelectedValue();
		updateTree();
		showScenes(selectedScene);
	}

	public void editScene() {

		Scene tmp = new Scene();
		tmp.setNr(selectedScene.getNr());
		tmp.setName(AppPanelScene.txtSceneName.getText());

		tmp.setDescription(AppPanelScene.taSceneDesc.getText());
		tmp.setDate(AppPanelScene.txtSceneMonth.getText() + "/"
				+ AppPanelScene.txtSceneDay.getText() + "/"
				+ AppPanelScene.txtSceneYear.getText());
		tmp.setLocation(AppPanelScene.dropSceneLocation.getSelectedItem()
				.toString());
		// TODO: add file dialog ...
		// open file dialog and get file
		// tmp.setFile(file);
		// tmp.setLocation(location);
		ArrayList<String> characters = new ArrayList<String>();
		for (int i = 0; i < selCharsList.getSize(); i++) {
			Object addchar = selCharsList.get(i);
			characters.add(addchar.toString());
		}
		tmp.setCharacters(characters);
		String status = (String) AppPanelScene.dropSceneStatus
				.getSelectedItem();
		tmp.setStatus(status);
		// TODO: check chapter and change ...
		// parse all plots
		for (int i = 0; i < activePlots.size(); i++) {
			Plot tmpPlot = activePlots.get(i);
			// does this plot contain this scene?
			if (tmpPlot.scenes.contains(selectedScene.toString())) {
				// should i change?
				if (AppPanelScene.dropScenePlot.getSelectedItem().toString()
						.equals(tmpPlot.toString()) == false) {
					tmpPlot.dbSceneDelete(dbFile, tmp.toString());
				}
			}
			if (tmpPlot.scenes.contains(selectedScene.toString()) == false) {
				// should I add?
				if (AppPanelScene.dropScenePlot.getSelectedItem().toString()
						.equals(tmpPlot.toString())) {
					tmpPlot.dbSceneAdd(dbFile, tmp.toString());
				}
			}
		}

		selectedChapter.dbSceneUpdate(dbFile, tmp.getNr() - 1, tmp);
		selectedChapter.scenes.set(tmp.getNr() - 1, tmp);
		activeChapters.set(selectedChapter.getNr() - 1, selectedChapter);

		updateTree();
		selectedScene = tmp;
		showScenes(selectedScene);
	}

	private void dialogSceneFile() {
		// TODO open new file dialog and set the selected file

	}

	private void removeCharFromScene() {
		Object tmp = listSelChars.getSelectedValue();
		allCharsList.addElement(tmp);
		selCharsList.removeElement(tmp);

	}

	private void removeAllCharsFromScene() {
		int y = selCharsList.getSize();
		for (int i = 0; i < y; i++) {
			Object tmp = selCharsList.get(0);
			allCharsList.addElement(tmp);
			selCharsList.removeElement(tmp);
		}

	}

	private void addCharsToScene() {
		Object tmp = listAllChars.getSelectedValue();
		selCharsList.addElement(tmp);
		allCharsList.removeElement(tmp);

	}

	private void addAllCharsToScene() {
		int y = allCharsList.getSize();
		for (int i = 0; i < y; i++) {
			Object tmp = allCharsList.get(0);
			selCharsList.addElement(tmp);
			allCharsList.removeElement(tmp);
		}

	}

	public void createCharacterOverview() {
		Character tmp = new Character();
		JTextField name = new JTextField();
		JTextField nick = new JTextField();
		JTextField firstname = new JTextField();
		Object[] message = { "Name:", name, "Nickname:", nick, "Firstname",
				firstname };

		JOptionPane pane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE,
				JOptionPane.OK_CANCEL_OPTION);
		pane.createDialog(null, "edit note").setVisible(true);
		tmp.setName(name.getText());
		tmp.setNickName(nick.getText());
		tmp.setFirstName(firstname.getText());
		String s = path.getLastPathComponent().toString();
		if (s.toString().equals("Main Cast")) {
			tmp.setRole("Main Cast");
		}
		if (s.toString().equals("Support Cast")) {
			tmp.setRole("Support Cast");
		}
		if (s.toString().equals("Extras")) {
			tmp.setRole("Extras");
		}
		if (tmp.getName().equals("") | tmp.getNickName().equals("")
				| tmp.getFirstName().equals("")) {
			StoryLineAppGUI.lblStatusOutput
					.setText("name, nickname and firstname required");
			return;
		} else {
			createCharacter(tmp);
		}
	}

	private void createCharacterPanel() {
		Character tmp = new Character();
		tmp.setAge(AppPanelCharacter.txtCharAge.getText());
		tmp.setDescription(AppPanelCharacter.taCharDesc.getText());
		Faction f = (Faction) AppPanelCharacter.dropCharFaction
				.getSelectedItem();
		tmp.setFaction(f.toString());
		tmp.setFirstName(AppPanelCharacter.txtFirstname.getText());
		tmp
				.setGender(AppPanelCharacter.dropGender.getSelectedItem()
						.toString());
		tmp.setImage(AppPanelCharacter.txtImageUrl.getText());
		tmp.setLevel(AppPanelCharacter.dropCharLevel.getSelectedItem()
				.toString());
		tmp.setName(AppPanelCharacter.txtName.getText());
		tmp.setNickName(AppPanelCharacter.txtNickname.getText());
		tmp
				.setRole(AppPanelCharacter.dropCharRole.getSelectedItem()
						.toString());
		createCharacter(tmp);

	}

	private void createCharacter(Character tmp) {

		tmp.dbCreateCharacter(dbFile);
		activeCharacters.add(tmp);
		updateTree();

	}

	public void deleteCharacterOverview() {
		try {
			deleteCharacter(selectedCharacter);
			updateTree();
			showCharacterOverview();
		} catch (NullPointerException e) {
			StoryLineAppGUI.lblStatusOutput.setText("nothing selected");
		}

	}

	public void deleteCharacter(Character c) {

		int n = JOptionPane.showConfirmDialog(panelLocacionOverview,
				"Do you really want to delete this?", "Warning",
				JOptionPane.OK_CANCEL_OPTION);
		if (n == JOptionPane.YES_OPTION) {
			selectedCharacter.dbDeleteCharacter(dbFile);
			activeCharacters.remove(c);
			updateTree();
			showCharacterOverview();
		}
	}

	public void editCharacterOverview(Character c) {
		updateTree();
		showCharacter(selectedCharacter);
	}

	public void editCharacter() {
		Character tmp = new Character();
		charsList.removeElement(selectedCharacter);
		tmp.setAge(AppPanelCharacter.txtCharAge.getText());
		tmp.setDescription(AppPanelCharacter.taCharDesc.getText());
		Faction f = (Faction) AppPanelCharacter.dropCharFaction
				.getSelectedItem();
		tmp.setFaction(f.toString());
		tmp.setFirstName(AppPanelCharacter.txtFirstname.getText());
		tmp
				.setGender(AppPanelCharacter.dropGender.getSelectedItem()
						.toString());
		tmp.setImage(AppPanelCharacter.txtImageUrl.getText());
		tmp.setLevel(AppPanelCharacter.dropCharLevel.getSelectedItem()
				.toString());
		tmp.setName(AppPanelCharacter.txtName.getText());
		tmp.setNickName(AppPanelCharacter.txtNickname.getText());
		tmp
				.setRole(AppPanelCharacter.dropCharRole.getSelectedItem()
						.toString());
		selectedCharacter.dbEditCharacter(dbFile, tmp);
		selectedCharacter = tmp;
		updateTree();
		showCharacter(selectedCharacter);
	}

	public void renumberChapters() {
		ArrayList<Chapter> chapters = activeChapters;
		ArrayList<Chapter> list = new ArrayList<Chapter>();
		for (int i = 0; i < chapters.size(); i++) {
			Chapter tmp = chapters.get(i);
			list.add(tmp);
		}
		activeChapters = list;

	}

	public void renumberScenes() {

		for (int y = 0; y < activeChapters.size(); y++) {
			Chapter c = activeChapters.get(y);
			ArrayList<Scene> scenes = c.getScenes();
			ArrayList<Scene> list = new ArrayList<Scene>();
			for (int i = 0; i < scenes.size(); i++) {
				Scene tmp = scenes.get(i);
				tmp.setNr(i + 1);
				list.add(tmp);
			}
			c.setScenes(list);
		}
	}

	public void expandChapters() {
		storytree.expandRow(1);
	}

	public void expandScenes() {
		// TODO: find the correct chapter and expand the tree
		int i = selectedChapter.getNr();
		storytree.expandRow(i + 1);
		storytree.expandRow(i + 2);
	}

	public void expandCharacters() {
		storytree.expandRow(2);
	}

	public void expandLocations() {
		storytree.expandRow(3);
	}

	public void expandFactions() {
		storytree.expandRow(4);
	}

	public void expandPlots() {
		storytree.expandRow(5);
	}

	public void expandNotes() {
		storytree.expandRow(6);
	}

	// the end

}
